package servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/ServletDemo3")
public class ServletDemo3 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //通过文件相对路径获取绝对路径
        String realPath = getServletContext().getRealPath("/img/3.jpg");
        System.out.println(realPath);

        //创建字节输入流对象，关联图片
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(realPath));

        //content-type消息头名称 支持类型   application/octet-stream 消息头参数
       // resp.setHeader("Content-Type","application/octet-stream");

        //通过响应对象获取字节输出流对象
        ServletOutputStream os = resp.getOutputStream();
        //读写
        byte[] bytes = new byte[1024];
        int len=0;
        while ((len=bis.read(bytes))!=-1){
            os.write(bytes,0,len);
        }
        //释放
        bis.close();
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      doGet(req, resp);
    }
}
